import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Table, Button, Input, Modal, Form, Space, message, Popconfirm, Tree } from 'antd';
import { PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined, KeyOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';

interface RoleData {
  key: number;
  id: number;
  name: string;
  code: string;
  description: string;
  createTime: string;
}

// 菜单树数据放在组件外部，避免重复创建
const menuTreeData: DataNode[] = [
  {
    title: '系统管理',
    key: 'system',
    children: [
      {
        title: '用户管理',
        key: 'system:user',
        children: [
          { title: '查询用户', key: 'system:user:list' },
          { title: '新增用户', key: 'system:user:add' },
          { title: '修改用户', key: 'system:user:edit' },
          { title: '删除用户', key: 'system:user:delete' },
        ],
      },
      {
        title: '角色管理',
        key: 'system:role',
        children: [
          { title: '查询角色', key: 'system:role:list' },
          { title: '新增角色', key: 'system:role:add' },
          { title: '修改角色', key: 'system:role:edit' },
          { title: '删除角色', key: 'system:role:delete' },
          { title: '分配权限', key: 'system:role:permission' },
        ],
      },
      {
        title: '菜单管理',
        key: 'system:menu',
        children: [
          { title: '查询菜单', key: 'system:menu:list' },
          { title: '新增菜单', key: 'system:menu:add' },
          { title: '修改菜单', key: 'system:menu:edit' },
          { title: '删除菜单', key: 'system:menu:delete' },
        ],
      },
    ],
  },
  {
    title: '内容管理',
    key: 'content',
    children: [
      { title: '文章管理', key: 'content:article' },
      { title: '分类管理', key: 'content:category' },
      { title: '标签管理', key: 'content:tag' },
    ],
  },
];

const RoleManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [dataSource, setDataSource] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<RoleData | null>(null);
  const [currentRole, setCurrentRole] = useState<RoleData | null>(null);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>(['system', 'content']);

  // 模拟获取角色列表 - 使用useCallback避免重复创建函数
  const fetchRoles = useCallback(async () => {
    setLoading(true);
    try {
      // 模拟API调用 - 在实际应用中替换为真实API调用
      const mockRoles: RoleData[] = [
        {
          key: 1,
          id: 1,
          name: '管理员',
          code: 'admin',
          description: '系统管理员，拥有所有权限',
          createTime: '2023-01-01 00:00:00',
        },
        {
          key: 2,
          id: 2,
          name: '普通用户',
          code: 'user',
          description: '普通用户，拥有基本操作权限',
          createTime: '2023-01-02 00:00:00',
        },
        {
          key: 3,
          id: 3,
          name: '访客',
          code: 'visitor',
          description: '访客，只有查看权限',
          createTime: '2023-01-03 00:00:00',
        },
      ];
      
      setTimeout(() => {
        setDataSource(mockRoles);
        setLoading(false);
      }, 300); // 减少模拟延迟时间
    } catch (error) {
      console.error('获取角色列表失败', error);
      message.error('获取角色列表失败');
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchRoles();
  }, [fetchRoles]);

  // 使用useCallback优化事件处理函数
  const handleSearch = useCallback(() => {
    const values = searchForm.getFieldsValue();
    // 模拟搜索，实际项目中应调用API
    const filtered = dataSource.filter(
      item => 
        (!values.name || item.name.includes(values.name)) && 
        (!values.code || item.code.includes(values.code))
    );
    setDataSource(filtered);
  }, [dataSource, searchForm]);

  const handleAdd = useCallback(() => {
    form.resetFields();
    setEditingRole(null);
    setModalVisible(true);
  }, [form]);

  const handleEdit = useCallback((record: RoleData) => {
    setEditingRole(record);
    form.setFieldsValue({
      name: record.name,
      code: record.code,
      description: record.description,
    });
    setModalVisible(true);
  }, [form]);

  const handleDelete = useCallback(async (id: number) => {
    try {
      // 模拟删除操作
      setDataSource(prev => prev.filter(item => item.id !== id));
      message.success('删除成功');
    } catch (error) {
      console.error('删除角色失败', error);
      message.error('删除角色失败');
    }
  }, []);

  const handleSave = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      if (editingRole) {
        // 更新角色
        setDataSource(prev => 
          prev.map(item => {
            if (item.id === editingRole.id) {
              return {
                ...item,
                name: values.name,
                code: values.code,
                description: values.description,
              };
            }
            return item;
          })
        );
        message.success('更新角色成功');
      } else {
        // 添加角色
        const newRole: RoleData = {
          key: Date.now(),
          id: Date.now(),
          name: values.name,
          code: values.code,
          description: values.description,
          createTime: new Date().toLocaleString(),
        };
        setDataSource(prev => [...prev, newRole]);
        message.success('添加角色成功');
      }
      
      setModalVisible(false);
    } catch (error) {
      console.error('表单验证失败', error);
    }
  }, [form, editingRole]);

  const handlePermission = useCallback((record: RoleData) => {
    setCurrentRole(record);
    // 模拟获取角色权限
    let rolePermissions: React.Key[] = [];
    if (record.code === 'admin') {
      rolePermissions = ['system', 'system:user', 'system:user:list', 'system:user:add', 'system:user:edit', 'system:user:delete',
        'system:role', 'system:role:list', 'system:role:add', 'system:role:edit', 'system:role:delete', 'system:role:permission',
        'system:menu', 'system:menu:list', 'system:menu:add', 'system:menu:edit', 'system:menu:delete',
        'content', 'content:article', 'content:category', 'content:tag'];
    } else if (record.code === 'user') {
      rolePermissions = ['system:user:list', 'content:article', 'content:category', 'content:tag'];
    } else if (record.code === 'visitor') {
      rolePermissions = ['system:user:list', 'content:article'];
    }
    setCheckedKeys(rolePermissions);
    setPermissionModalVisible(true);
  }, []);

  const handlePermissionSave = useCallback(() => {
    if (currentRole) {
      message.success(`已为角色 ${currentRole.name} 分配权限`);
      setPermissionModalVisible(false);
    }
  }, [currentRole]);

  // 使用useMemo优化表格列定义
  const columns = useMemo(() => [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: RoleData) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" icon={<KeyOutlined />} onClick={() => handlePermission(record)}>
            权限
          </Button>
          <Popconfirm
            title="确定要删除此角色吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [handleDelete, handleEdit, handlePermission]);

  return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="mb-4">
        <Form form={searchForm} layout="inline">
          <Form.Item name="name" label="角色名称">
            <Input placeholder="请输入角色名称" allowClear />
          </Form.Item>
          <Form.Item name="code" label="角色编码">
            <Input placeholder="请输入角色编码" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      
      <div className="mb-4">
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增角色
        </Button>
      </div>
      
      <Table
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        rowKey="id"
        pagination={{ 
          pageSize: 10,
          showSizeChanger: false // 禁用页码大小切换器减少不必要的渲染
        }}
      />

      {/* 角色表单模态框 */}
      <Modal
        title={editingRole ? '编辑角色' : '新增角色'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        maskClosable={false}
        destroyOnClose // 关闭时销毁Modal内容，避免残留状态
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="code"
            label="角色编码"
            rules={[{ required: true, message: '请输入角色编码' }]}
          >
            <Input placeholder="请输入角色编码" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入描述" rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限分配模态框 */}
      <Modal
        title={`分配权限 - ${currentRole?.name}`}
        open={permissionModalVisible}
        onOk={handlePermissionSave}
        onCancel={() => setPermissionModalVisible(false)}
        width={600}
        maskClosable={false}
        destroyOnClose // 关闭时销毁Modal内容
      >
        <div className="mb-4">
          <p>请选择 {currentRole?.name} 角色的权限：</p>
        </div>
        <Tree
          checkable
          checkStrictly
          defaultExpandAll
          expandedKeys={expandedKeys}
          onExpand={setExpandedKeys}
          checkedKeys={checkedKeys}
          onCheck={(checked: any) => setCheckedKeys(checked)}
          treeData={menuTreeData}
        />
      </Modal>
    </div>
  );
};

export default React.memo(RoleManagement); // 使用React.memo包裹组件减少不必要的重渲染 
